package yang.learn.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import yang.learn.entity.ChatRoom;
import yang.learn.entity.ChatRoomRecord;
import yang.learn.service.ChatRoomRecordService;

import java.util.List;

@Controller
@RequestMapping("/chat/room/record")
public class ChatRoomRecordController {
    @Autowired(required = false)
    private ChatRoomRecordService chatRoomRecordService;

    @RequestMapping("/list")
     public String list(HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        //服务端备份聊天室信息
        int chat_id = Integer.parseInt(String.valueOf(session.getAttribute("chat_id")));
        //查询用户发与联系人的信息
        List<ChatRoomRecord> chatRoomRecordList = chatRoomRecordService.queryAll(new ChatRoom(chat_id,0,0,0,""));
        System.out.println(chat_id+"聊天室的聊天记录"+chatRoomRecordList);
        model.addAttribute("chatRoomRecordList",chatRoomRecordList);
        return "/chatroom/record.html :: chat";
    }

    @RequestMapping("/add")
    public ModelAndView add(HttpServletRequest request,@RequestBody ChatRoomRecord chatRoomRecord){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("chatroom/add");
        HttpSession session = request.getSession();
        //服务端备份用户信息
        int user_id = Integer.parseInt(String.valueOf(session.getAttribute("user_id")));
        String user_name = String.valueOf(session.getAttribute("user_name"));
        int chatroom_id = Integer.parseInt(String.valueOf(session.getAttribute("chat_id")));
        System.out.println("给聊天室"+chatroom_id+"消息内容"+chatRoomRecord.getChat_context());
        chatRoomRecordService.add(
                new ChatRoomRecord(chatroom_id,user_id,user_name,chatRoomRecord.getChat_context()));
        return modelAndView;
    }


}
